<?php

namespace Drupal\shusy_sweepstake\Entity;

use Drupal\shusy_sweepstake\ViewsController\Traits\ShusySweepstakeStatusTrait;
use Entity;

class ShusySweepstake extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $name;

  public $content;

  public $validity_start = 0;

  public $validity_end = 0;

  public $status = 0;

  use ShusySweepstakeStatusTrait;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_sweepstake');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }
    //只能启用一个
    if ($this->status == 1) {
      $es = shusy_sweepstake_load_multiple(FALSE, ['status' => 1]);
      foreach ($es as $e) {
        if ($e instanceof ShusySweepstake) {
          if ($e->id != $this->id) {
            $e->status = 0;
            $e->save();
          }
        }
      }
    }
    return parent::save();
  }

}
